import { createI18n } from "vue-i18n";
import { LANG } from '@views/fabric/configs/key'
import { getLocal, setLocal } from '@views/fabric/utils/local';
import zh from "./lang/zh";
import en from "./lang/en";

const getLocalLang = () => {
	let localLang = getLocal(LANG);
	if (!localLang) {
	  let defaultLang = navigator.language;
	  if (defaultLang) {
		const _lang = defaultLang.split('-')[0]
		defaultLang = _lang;
		localLang = _lang;
		setLocal(LANG, _lang)
	  }
	}
	return localLang;
}

const createI18nOptions = () => {
	const locale = getLocalLang();
	const messages= {
		zh,
		en
	}

	return {
	  legacy: false,
	  locale,
	  messages,
	  allowComposition: true,
	  globalInjection: true,
	  silentTranslationWarn: true, // true - warning off
	  missingWarn: false,
	  silentFallbackWarn: false,
	};
}
const options = createI18nOptions();

const i18n = createI18n(options);


const setI18nLanguage = (locale) => {
  if (i18n?.mode === 'legacy') {
    i18n.global.locale = locale;
  } else {
    (i18n?.global.locale).value = locale;
  }
  setLocal(LANG, locale);
}

export const changeLocale = async (locale) => {
  const globalI18n = i18n?.global;
  if(!globalI18n) return
  const currentLocale = globalI18n.locale;
  if (currentLocale === locale) return;
  setI18nLanguage(locale);
  return locale;
}

export const i18nObj = () => {
  const localeData = createI18nOptions()
  return createI18n(localeData)
} 

export default i18n;